<?php
namespace app\home\controller;

use app\common\component\message\MessageService;

class Message extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

	public function index() {
		$this -> view -> assign('messages', (new MessageService) -> getMessages(10, true));

		return $this -> view -> fetch();
	}

	public function detail() {
		$resultMessage = (new MessageService) -> getMessage($this -> request -> get('message_id', 1, 'int'));
		$this -> view -> assign('message', $resultMessage['data']['message']);

		return $this -> view -> fetch();		
	}

	public function save() {
		if($this -> request -> isPost()) {
			$post = $this -> request -> post();
			$post['user_id'] = \think\Session::get('user_id');
			$post['create_time'] = time();
			$post['pic'] = uploadFile();
			$post['replay_content'] = '';

			$resultMessage = (new MessageService) -> create($post);
			if($resultMessage['code'] !== 0) {
				echo '<meta charset="utf-8"><script>alert(' . $resultMessage['message'] . ');window.history.go(-1);</script>';exit;
			}
			echo '<meta charset="utf-8"><script>window.location.href="/message";</script>';exit;
		}
		return $this -> view -> fetch();
	}
}